﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using DotNetCore.CAP;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NetCoreMicroserviceDemo.CommonLib.MessageDto;
using Order.API.Models;

namespace Order.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class OrdersController : ControllerBase
    {
        private readonly ILogger<OrdersController> m_Logger;
        private readonly IConfiguration m_configuration;
        private readonly ICapPublisher m_capBus;
        private readonly OrderContext m_orderContext;

        public OrdersController(ILogger<OrdersController> logger, IConfiguration configuration, ICapPublisher capPublisher,OrderContext orderContext)
        {
            m_Logger = logger;
            m_configuration = configuration;
            m_capBus = capPublisher;
            m_orderContext = orderContext;
        }

        public IActionResult Get()
        {
            string result = @$"【订单服务】{DateTime.Now:yyyy-MM-dd HH:mm:ss}--" +
                            $"{Request.HttpContext.Connection.LocalIpAddress}:" +
                            $"{m_configuration["ConsulSetting:ServicePort"]}";
            return Ok(result);
        }

        /// <summary>
        /// 下单 发布下单事件
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        [Route("Create")]
        [HttpPost]
        public async Task<IActionResult> CreateOrder(Order.API.Models.Order order)
        {
            
            using (var trans=m_orderContext.Database.BeginTransaction(m_capBus,autoCommit:true))
            {
                order.CreateTime = DateTime.Now;
                m_orderContext.Orders.Add(order);
                m_Logger.LogInformation($"CreateOrder: Orders.Add Id {order.ID} ProductID:{order.ProductID} Count:{order.Count}");
                var r = await m_orderContext.SaveChangesAsync() > 0;
                if (r)
                {
                    await m_capBus.PublishAsync("order.services.createorder", new CreateOrderMessageDto() {
                    Count=order.Count,
                    ProductID=order.ProductID
                    });
                    return Ok();
                }
                return BadRequest();
            }
        }
    }
}
